# -*- coding: utf-8 -*-
from . import BaseController
from backend.models import BMSUser
from django.contrib.auth.signals import user_logged_in
from backend.libs import myjson as json
from hashlib import md5


class Login(BaseController):
    def post(self):
        data = json.loads(self.request.body)
        password = data.get('password')
        username = data.get('username')
        if not username or not password:
            return self.render_json(code=-1, msg='无效的用户名或密码')
        user = BMSUser.objects.filter(username=data.get('username')).first()
        if not user or not user.check_password(password):
            self.render_json(code=-1, msg='无效的用户名或密码')
        elif not user.is_active:
            self.render_json(code=-1, msg='用户被锁定')
        else:
            user_logged_in.send(sender=user.__class__, user=user)
            return self.render_json(data=user.to_login_dict())


class Logout(BaseController):
    def post(self):
        # to-do: 实现用户token的删除操作
        return self.render_json()


class UserInfo(BaseController):
    def get(self):
        current_user = self.current_user
        if not current_user:
            return self.render_json(code=50008, msg='非法的token')
        return self.render_json(data=current_user.to_user_info_dict())